import {PlusOutlined} from '@ant-design/icons';
import {Button, Divider, message, Input, Drawer, InputNumber, Select, Form, Modal, Tag} from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import React, {useState, useRef} from 'react';
import {PageContainer, FooterToolbar} from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import ProDescriptions from '@ant-design/pro-descriptions';
import ClientForm from './components/ClientForm';
import {queryRule, updateRule, addRule, removeRule, enable, disable} from './service';


const TableList = () => {
  const [createModalVisible, handleModalVisible] = useState(false);
  const [selectedRow, setSelectedRow] = useState({});
  const [formTitle, setFormTitle] = useState('新增客户');
  const actionRef = useRef();
  const [formRef] = Form.useForm();
  const [row, setRow] = useState();
  const [selectedRowsState, setSelectedRows] = useState([]);
  const { Option } = Select;
  const handleUpdateModalVisible = (record)=>{
    setSelectedRow(record)
    formRef.setFieldsValue({
      ...record
    })
    setFormTitle('更新客户')
    handleModalVisible(true)
  }
  const handleCreateModalVisible = ()=>{
    setFormTitle('新增客户')
    handleModalVisible(true)
  }

  const handleAdd = async (fields) => {
    const hide = message.loading('正在添加');

    try {
      hide();
      await addRule({...fields}).then((res) => {
        if (res && res.status === '0') {
          handleModalVisible(false)
          message.success(res.message);
        } else {
          message.error(res.message);
        }
      });
      return true;
    } catch (error) {
      hide();
      message.error('添加失败请重试！');
      return false;
    }

    return true;
  };

  const handleUpdate = async (fields) => {
    const hide = message.loading('正在更新');

    try {
      hide();
      await updateRule({...fields, custId: selectedRow.custId}).then((res) => {
        if (res && res.status === '0') {
          handleModalVisible(false)
          message.success(res.message);
        } else {
          message.error(res.message);
        }
      });
      return true;
    } catch (error) {
      hide();
      message.error('更新失败请重试！');
      return false;
    }
  };

  const handleRemove = async (selectedRows) => {
    const hide = message.loading('正在删除');
    if (!selectedRows) return true;

    try {
      hide();
      await removeRule({...selectedRows}).then((res) => {
        if (res && res.status === '0') {
          handleModalVisible(false)
          message.success(res.message);
        } else {
          message.error(res.message);
          return false;
        }
        return true;
      });
      return true;
    } catch (error) {
      hide();
      message.error('删除失败请重试！');
      return false;
    }

  };

  const handleEnable = async (fields) => {
    try {
      if (fields.status === 1) {
        await disable({...fields}).then((res) => {
          if (res && res.status === '0') {
            message.success(res.message);
          } else {
            message.error(res.message);
            return false;
          }
          return true;
        });
      }else {
        await enable({...fields}).then((res) => {
          if (res && res.status === '0') {
            message.success(res.message);
          } else {
            message.error(res.message);
            return false;
          }
          return true;
        });
      }
      if (actionRef.current) {
        actionRef.current.reload();
      }

    } catch (error) {
      message.error('请联系管理员');
      return false;
    }
    return true;
  }

  const deleteConfig = (record) => {
    Modal.confirm({
      title: '注意',
      icon: <ExclamationCircleOutlined/>,
      content: `是否要删除客户编码为 【${record.custCode} 】的客户？`,
      okText: '确认',
      cancelText: '取消',
      onOk: async ()=>{
        const success = await handleRemove(record)
        if (success) {
          if (actionRef.current) {
            actionRef.current.reload();
          }
        }
      }
    });
  };


  const columns = [
    {
      title: '序号',
      dataIndex: 'key',
      hideInForm: true,
      hideInSearch: true,
      render: (text, record, index, action) => {
        return `${index + 1}`
      }
    },
    {
      title: '客户编码',
      dataIndex: 'custCode',
      tip: '客户编码是唯一的',
      hideInForm: formTitle === '新增客户',
      copyable: true,
      formItemProps: {
        rules: [
          {
            whitespace: true,
            message: '请不要输入空格'
          },
          {
            required: true,
            message: '客户编码是必填项'
          },
          {
            max: 32,
            message: '最大长度为32'
          },
        ],
      },
      valueType: 'input',
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return <Input disabled={type === 'form'} {...fieldProps} placeholder={'请输入客户编码 格式为A0'}/>;
      }
    },
    {
      title: '客户名称',
      dataIndex: 'custName',
      copyable: true,
      formItemProps: {
        rules: [
          {
            max: 32,
            message: '客户名称最大长度为32'
          },
          {
            whitespace: true,
            message: '请不要输入空格'
          },
          {
            required: true,
            message: '客户名称是必填项'
          }
        ],
      },
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return <Input placeholder={'请输入客户名称'}/>;
      }
    },
    {
      title: '客户地址',
      dataIndex: 'custAddress',
      hideInSearch: true,
      formItemProps: {
        rules: [
          {
            max: 32,
            message: '客户地址最大长度为32'
          },
        ],
      },
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return <Input placeholder={'请输入客户地址'}/>;
      }
    },
    {
      title: '可欠月结款月数（月）',
      dataIndex: 'accountReceiveMonths',
      sorter: true,
      hideInSearch: true,
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return <InputNumber min={1} style={{width: '100%'}}/>;
      }
    },
    {
      title: '逾期预警天数（天）',
      dataIndex: 'accountReceiveWarningDays',
      sorter: true,
      hideInSearch: true,
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return <InputNumber min={1} style={{width: '100%'}}/>;
      }
    },
    {
      title: '状态',
      dataIndex: 'status',
      sorter: true,
      hideInForm: true,
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return <Select defaultValue={-1}>
          <Option value={-1}>全部</Option>
          <Option value={0}>禁用</Option>
          <Option value={1}>启用</Option>
        </Select>;
      },
      render: (text, record, index) => {
        return (
          <Tag color={text === 1 ? 'green' : 'red'
          }>{text === 1 ? '启用' : '禁用'}</Tag>
        )
      }
    },
    {
      title: '创建人',
      dataIndex: 'createName',
      hideInSearch: true,
      hideInForm: true
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      sorter: true,
      valueType: 'dateTime',
      hideInSearch: true,
      hideInForm: true
    },
    {
      title: '备注',
      dataIndex: 'remark',
      valueType: 'textarea',
      hideInSearch: true,
      hideInTable: true
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a onClick={() => setRow(record)}>
          详情
        </a>,
        <Divider type="vertical"/>,
        <a onClick={() => handleUpdateModalVisible(record)}>修改</a>,
        <Divider type="vertical"/>,
        <a onClick={()=> handleEnable(record)}>{record.status === 1? '禁用': '启用'}</a>,
        <Divider type="vertical"/>,
        <a onClick={()=> deleteConfig(record) }>删除</a>,
      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable
        actionRef={actionRef}
        rowKey="custId"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button type="primary" onClick={() => handleCreateModalVisible()}>
            <PlusOutlined/> 新建
          </Button>,
        ]}
        request={async (params, sorter, filter) => {
          const param = {...params, pageNum: params.current};
          if (param.status === -1) {
            param.status = null;
          }
          const res = await queryRule(param)
          return {
            data: res.result.records,
            success: true,
            total: res.result.total
          }
        }}
        columns={columns}
        // rowSelection={{
        //   onChange: (_, selectedRows) => setSelectedRows(selectedRows),
        // }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a
                style={{
                  fontWeight: 600,
                }}
              >
                {selectedRowsState.length}
              </a>{' '}
              项&nbsp;&nbsp;
              <span>
                服务调用次数总计 {selectedRowsState.reduce((pre, item) => pre + item.callNo, 0)} 万
              </span>
            </div>
          }
        >
          <Button
            onClick={async () => {
              await handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            批量删除
          </Button>
          <Button type="primary">批量审批</Button>
        </FooterToolbar>
      )}
      <ClientForm title={formTitle} onCancel={() => handleModalVisible(false)} modalVisible={createModalVisible}>
        <ProTable
          onSubmit={async (value) => {

            const success = formTitle === '新增客户'?await handleAdd(value): await handleUpdate(value)

            if (success) {
              handleModalVisible(false);

              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          form={{
            form: formRef,
            layout: 'horizontal',
            labelAlign: 'left'
          }}
          rowKey="key"
          type="form"
          columns={columns}
        />
      </ClientForm>

      <Drawer
        width={600}
        visible={!!row}
        onClose={() => {
          setRow(undefined);
        }}
        closable={false}
      >
        {row?.custCode && (
          <ProDescriptions
            column={2}
            title={row?.custCode}
            request={async () => ({
              data: row || {},
            })}
            params={{
              id: row?.custCode,
            }}
            columns={columns}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default TableList;
